package com.itesm.distribuidos.mexicantrain;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.text.MaskFormatter;

public class ServerGUI extends JFrame{
	private static final long serialVersionUID = 1L;
	private JLabel playersLabel;
	private JFormattedTextField players;
	private JLabel delayLabel;
	private JFormattedTextField delay;
	private JButton button;
	private JTextArea console;
	private JPanel upperPanel, mainPanel;
	private JScrollPane scrollConsole;
	private MexicanTrainServer serverInstance;

	public ServerGUI() {
		super("Mexican Train Server");
		initComponents();
	}

	private void initComponents() {
		playersLabel = new JLabel();
		playersLabel.setText("Number of Players: ");
		playersLabel.setBounds(10, 20, 200, 30);

		try {
			MaskFormatter mask = new MaskFormatter("#");
			players = new JFormattedTextField(mask);
		} catch (ParseException e){}

		players.setValue(new Integer(2));
        players.setToolTipText("Number of players from 2 to 8");
        players.setBounds(220, 20, 232, 30);

        delayLabel = new JLabel();
        delayLabel.setText("Delay to start: ");
        delayLabel.setBounds(10, 100, 200, 30);

		try {
			MaskFormatter mask = new MaskFormatter("##");
			delay = new JFormattedTextField(mask);
		} catch (ParseException e){}

		delay.setValue(new Integer(20));
		delay.setToolTipText("Delay in seconds");
        delay.setBounds(220, 100, 232, 30);

		button = new JButton();
		serverInstance = null;
		
		console = new JTextArea("");
		scrollConsole = new JScrollPane(console);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        upperPanel = new JPanel(new GridLayout(2,2));
        upperPanel.add(playersLabel);
        upperPanel.add(players);
        upperPanel.add(delayLabel);
        upperPanel.add(delay);
        upperPanel.setBorder(BorderFactory.createEmptyBorder(15,15,35,35));

        mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(upperPanel,BorderLayout.NORTH);
        mainPanel.add(scrollConsole,BorderLayout.CENTER);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        getContentPane().add(mainPanel,BorderLayout.CENTER);
        button.setText("Start Server");
        getContentPane().add(button,BorderLayout.SOUTH);
        button.setBounds(130, 180, 232, 50);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
            	if(button.getText().equals("Start Server"))
            	{
            		serverInstance = new MexicanTrainServer((Integer)players.getValue(),getFrame());
            		serverInstance.start();
            		
            		ActionListener taskPerformer = new ActionListener() {
            			@Override
            			public void actionPerformed(ActionEvent arg0) {
            				updateConsole("Time is Over! Let's start to play");
            				if(serverInstance.getNumPlayers()<=1)
            				{
            					String message = "Can not start a game with less than 2 players. \n Waiting for " + players.getValue() + " players.";
            					JOptionPane.showMessageDialog(null, message, "Start Game" ,JOptionPane.INFORMATION_MESSAGE);
            				}
            				else
            				{
            					serverInstance.startGame();
            				}
            			}
            		  };
            		  Timer timer = new Timer(((Integer)delay.getValue() * 1000) , taskPerformer);
            		  timer.setRepeats(false);
            		  timer.start();
            		  
            		button.setText("Stop Server");
            	}
            	else
            	{
            		if(serverInstance != null)
            		{
            			serverInstance.stopServer();
            			button.setText("Start Server");
            		}
            	}
            }
        });
        setBounds(Toolkit.getDefaultToolkit().getScreenSize().width/3,Toolkit.getDefaultToolkit().getScreenSize().height/12,500,600);
        setVisible(true);
    }

	public ServerGUI getFrame() {
		return this;
	}

	public void updateConsole(String data) {
		console.append(data+"\n");
	}

	public static void main(String...arg)
	{
		new ServerGUI();
	}
}
